package com.whz.workmanageol.service.impl;

import com.whz.workmanageol.dao.CourseMapper;
import com.whz.workmanageol.dao.GradeCourseMapper;
import com.whz.workmanageol.dao.GradeMapper;
import com.whz.workmanageol.dao.TeacherMapper;
import com.whz.workmanageol.entity.Course;
import com.whz.workmanageol.entity.Grade;
import com.whz.workmanageol.entity.GradeCourse;
import com.whz.workmanageol.entity.Teacher;
import com.whz.workmanageol.service.TeacherService;
import com.whz.workmanageol.vo.GradeCourseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Service
@Transactional
public class TeacherServiceImpl implements TeacherService {
    @Autowired
    private GradeMapper gradeMapper;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private GradeCourseMapper gradeCourseMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Override
    public List<GradeCourseVO> getGradeCourseByTea(String teacherid) {
        List<Grade> gradeList = gradeMapper.findGradesByTeacherid(teacherid);
        List<Course> courseList = courseMapper.findCourseByTeacherid(teacherid);
        List<GradeCourseVO> gradeCourseVOList = new ArrayList<>();
        GradeCourseVO gradeCourseVO = null;
        for(Grade grade : gradeList){
            gradeCourseVO = new GradeCourseVO();
            gradeCourseVO.setId(grade.getId());
            gradeCourseVO.setGradeid(grade.getGradeid());
            gradeCourseVO.setGradename(grade.getGradename());
            List<Course> courses = new ArrayList<>();
            for(Course course : courseList){
                GradeCourse gradeCourse = new GradeCourse();
                gradeCourse.setCourseid(course.getId());
                gradeCourse.setGradeid(grade.getId());
                if(gradeCourseMapper.selectCount(gradeCourse) > 0){
                    courses.add(course);
                }
            }
            Collections.sort(courses, Comparator.comparing(Course::getCoursename));
            gradeCourseVO.setCourseList(courses);
            gradeCourseVOList.add(gradeCourseVO);

        }
        Collections.sort(gradeCourseVOList, Comparator.comparing(GradeCourseVO::getGradename));
        return gradeCourseVOList;
    }

    @Override
    public Teacher findTeacherById(String id) {
        return teacherMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Course> findCourseByGradeIdAndTeacherId(String gradeId, String teacherId) {
        return courseMapper.findCourseByGradeIdAndTeacherId(gradeId, teacherId);
    }
}
